package com.demo2do.fms.admin.web.controller.supplier.sub.flow;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.page.Page;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.utils.WebUtils;
import com.demo2do.fms.admin.entity.search.supplier.SupplierAuditSearch;
import com.demo2do.fms.admin.entity.security.Login;
import com.demo2do.fms.admin.service.supplier.SupplierAuditService;
import com.demo2do.fms.admin.service.supplier.SupplierBusinessHistoryService;
import com.demo2do.fms.admin.service.supplier.SupplierCertificateService;
import com.demo2do.fms.admin.service.supplier.SupplierInfoService;
import com.demo2do.fms.admin.service.supplier.SupplierParkingResourceService;
import com.demo2do.fms.admin.service.supplier.SupplierService;
import com.demo2do.fms.admin.service.supplier.SupplierStaffService;
import com.demo2do.fms.admin.service.supplier.TransSupplierService;
import com.demo2do.fms.admin.service.supplier.TransSupplierVehicleStatService;
import com.demo2do.fms.admin.service.supplier.WareSupplierEmployeeService;
import com.demo2do.fms.admin.service.supplier.WareSupplierService;
import com.demo2do.fms.admin.web.resolver.Secure;
import com.demo2do.fms.entity.supplier.common.AuditStatus;
import com.demo2do.fms.entity.supplier.common.Supplier;
import com.demo2do.fms.entity.supplier.common.SupplierBusinessHistory;
import com.demo2do.fms.entity.supplier.common.SupplierCertificate;
import com.demo2do.fms.entity.supplier.common.SupplierEvent;
import com.demo2do.fms.entity.supplier.common.SupplierEventType;
import com.demo2do.fms.entity.supplier.common.SupplierInfo;
import com.demo2do.fms.entity.supplier.common.SupplierModifiedVersion;
import com.demo2do.fms.entity.supplier.common.SupplierParkingResource;
import com.demo2do.fms.entity.supplier.common.SupplierRecommendation;
import com.demo2do.fms.entity.supplier.common.SupplierStaff;
import com.demo2do.fms.entity.supplier.trans.TransSupplier;
import com.demo2do.fms.entity.supplier.trans.TransSupplierVehicleStat;
import com.demo2do.fms.entity.supplier.ware.WareSupplier;
import com.demo2do.fms.entity.supplier.ware.WareSupplierEmployee;

/**
 * 分属供方申报审核
 * 
 * 只有总部有权限，
 * 可以查看申报的二级供方及引入其申报的一级供方
 * 可以查看申报的一级供方及引入其申报的分区供方
 * 看到申报的类型
 * 
 * @author Wy
 *
 */
@Controller
@RequestMapping("/supplier-declaration-audits")
@MenuSetting("menu-supplier")
public class SupplierDeclarationAuditController {
    
    private static final Logger logger = LoggerFactory.getLogger(SupplierDeclarationAuditController.class);
    
    @Autowired
    private SupplierAuditService supplierAuditService;
    
    @Autowired
    private SupplierService supplierService;
    
    @Autowired
    private SupplierInfoService supplierInfoService;
    
    @Autowired
    private SupplierCertificateService supplierCertificateService;
    
    @Autowired
    private SupplierBusinessHistoryService supplierBusinessHistoryService;
    
    @Autowired
    private SupplierParkingResourceService supplierParkingResourceService;
    
    @Autowired
    private SupplierStaffService  supplierStaffService;
    
    @Autowired
    private TransSupplierVehicleStatService transSupplierVehicleStatService;
    
    @Autowired
    private TransSupplierService transSupplierService;
    
    @Autowired
    private WareSupplierService wareSupplierService;
    
    @Autowired
    private WareSupplierEmployeeService wareSupplierEmployeeService;
    
    /**
     * list
     * 
     * @param status
     * @param syncStatus
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET )
    @MenuSetting("submenu-auditing-supplier-management")
    public ModelAndView list(@RequestParam(value = "status", required = false, defaultValue = "auditing") String status,
                             @RequestParam(value = "syncStatus", required = false) String syncStatus,
                             HttpServletRequest request, Page page) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier-declaration/supplier-declaration-audit-list");
        
        AuditStatus auditStatus = AuditStatus.aliasOf(status);
        modelAndView.addObject("supplierStatus", status);
        
        int totals = supplierAuditService.countSupplierByStatus(auditStatus, syncStatus);
        if(totals > 0) {
            
            List<Supplier> suppliers = supplierAuditService.listSupplierByStatus(auditStatus, syncStatus, page);
            
            modelAndView.addObject("suppliers", suppliers);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
    }
    
    /**
     * view search
     * 
     * @param status
     * @return
     */
    @RequestMapping(value = "/search" , method = RequestMethod.GET)
    public ModelAndView search(@RequestParam("status") String status) {
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier-declaration/supplier-declaration-audit-search");
        
        modelAndView.addObject("status", status);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param status
     * @param supplierAuditSearch
     * @param request
     * @param page
     * @return
     */
    @RequestMapping(value = "" , method = RequestMethod.GET  , params = "filter")
    @MenuSetting("submenu-auditing-supplier-management")
    public ModelAndView onSearch(@RequestParam("status") String status, SupplierAuditSearch supplierAuditSearch, 
                                 HttpServletRequest request, Page page){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier-declaration/supplier-declaration-audit-list");
        
        AuditStatus currentStatus = AuditStatus.aliasOf(status);
        AuditStatus[] auditStatus = new AuditStatus[]{currentStatus};
        supplierAuditSearch.setAuditStatus(auditStatus);
        
        int totals = supplierService.count(Supplier.class, supplierAuditSearch.getFilter());
        if(totals > 0) {
            
        	List<Supplier> suppliers = supplierAuditService.searchSupplier(supplierAuditSearch, page);
            
            modelAndView.addObject("suppliers", suppliers);
            modelAndView.addObject("page", page);
            modelAndView.addObject("queryString", WebUtils.extractQueryString(request, "page", "filter"));
            
        }
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param supplierId
     * @return
     */
    @RequestMapping(value = "/{supplierId}", method = RequestMethod.GET)
    @MenuSetting("submenu-auditing-supplier-management")
    public ModelAndView view(@PathVariable("supplierId") Long supplierId) {

        ModelAndView modelAndView = new ModelAndView();
        
        //运输和仓储公共的字段 
        Supplier supplier = supplierService.load(Supplier.class, supplierId);
        SupplierCertificate SupplierCertificate = supplierCertificateService.getSupplierCertificate(supplierId);
        SupplierInfo supplierInfo = supplierInfoService.load(supplierId);
        List<SupplierBusinessHistory> supplierBusinessHistorys = supplierBusinessHistoryService.listSupplierBusinessHistory(supplierId);
        List<SupplierParkingResource> parkingResources = supplierParkingResourceService.listSupplierParkingResource(supplierId);
        List<SupplierStaff> supplierStaffs = supplierStaffService.listSupplierStaff(supplierId);
      
        SupplierRecommendation recommendation = supplierService.getSupplierRecommendation(supplierId);
        
        SupplierModifiedVersion version = supplierService.getSupplierModifiedVersion(supplier);
        modelAndView.addObject("version", version);
        
        modelAndView.addObject("supplier", supplier);
        modelAndView.addObject("supplierCertificate", SupplierCertificate);
        modelAndView.addObject("supplierInfo", supplierInfo);
        modelAndView.addObject("supplierBusinessHistorys", supplierBusinessHistorys);
        modelAndView.addObject("parkingResources", parkingResources);
        modelAndView.addObject("supplierStaffs", supplierStaffs);
        modelAndView.addObject("recommendation", recommendation);
        modelAndView.addObject("supplierMenuType", "auditing");
       
        //运输供方
        if (supplier.getType().getAlias().equalsIgnoreCase("motor")) {

            modelAndView.setViewName("supplier/profile/supplier-profile-declaration-view");

            List<TransSupplierVehicleStat> transSupplierVehicleStats = transSupplierVehicleStatService.listTransSupplierVehicleStat(supplierId);
            TransSupplier transSupplier = transSupplierService.getTransSupplier(supplierId);
            SupplierEvent supplierEvent = supplierService.getSupplierEvent(supplierId, SupplierEventType.INTRODUCE_REJECTED);

            modelAndView.addObject("transSupplierVehicleStats", transSupplierVehicleStats);
            modelAndView.addObject("transSupplier", transSupplier);
            modelAndView.addObject("supplierEvent", supplierEvent);

        } else {

            modelAndView.setViewName("supplier/profile/supplier-profile-declaration-storage-view");

            WareSupplier wareSupplier = wareSupplierService.getWareSupplier(supplierId);
            List<WareSupplierEmployee> wareSupplierEmployees = wareSupplierEmployeeService.listWareSupplierEmployee(supplierId);

            modelAndView.addObject("wareSupplier", wareSupplier);
            modelAndView.addObject("wareSupplierEmployees", wareSupplierEmployees);

        }
       
        return modelAndView;
        
    }
    
    /**
     * 通过panel
     * 
     * @param supplierId
     * @param status
     * @return
     */
    @RequestMapping(value = "/{id}/adopt" , method = RequestMethod.GET)
    public ModelAndView adopt(@PathVariable("id") Long supplierId, @RequestParam("status") String status){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier-declaration/supplier-declaration-audit-adopt");
        
        modelAndView.addObject("supplierId", supplierId);
        modelAndView.addObject("status", status);
        
        return modelAndView;
    }

    /**
     * 通过
     * 
     * @param login
     * @param supplierId
     * @param status
     * @return
     */
    @RequestMapping(value = "/{id}/adopt" , method = RequestMethod.PATCH , produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onAdopt(@Secure(property = "id") Long operator,
                                            @PathVariable("id") Long supplierId,
                                            @RequestParam("status") String status){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            Supplier supplier = supplierService.load(Supplier.class, supplierId);
            if(StringUtils.equals(status, "auditing")) {
                supplierAuditService.onAdopt(supplier, operator);
            } else if (StringUtils.equals(status, "qualified")) {
                supplierAuditService.changingAdopt(supplier, operator);
            }
            
            httpResult.success().message("审核通过");
            
        } catch (Exception e) {
            logger.error("#onAdopt() - adopt fail, exception={}", e);
            httpResult.fail("500").message("审核失败！" + e.getMessage());
        }
        
        return httpResult;
        
    }
    
    /**
     * 驳回panel
     * 
     * @param supplierId
     * @param status
     * @return
     */
    @RequestMapping(value = "/{id}/reject" , method = RequestMethod.GET)
    public ModelAndView reject(@PathVariable("id") Long supplierId,
                               @RequestParam("status") String status){
        
        ModelAndView modelAndView = new ModelAndView("supplier/sub/flow/supplier-declaration/supplier-declaration-audit-reject");
        
        modelAndView.addObject("supplierId", supplierId);
        modelAndView.addObject("status", status);
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param supplierId
     * @param status
     * @param comment
     * @return
     */
    @RequestMapping(value = "/{id}/reject" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onReject(@Secure Login login,
                                             @PathVariable("id") Long supplierId,
                                             @RequestParam("status") String status,
                                             @RequestParam("comment") String comment){
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            Supplier supplier = supplierService.load(Supplier.class, supplierId);
            if(StringUtils.equals(status, "auditing")) {
                supplierAuditService.introduceReject(supplier, comment, login.getId());
            } else if (StringUtils.equals(status, "qualified")) {
                supplierAuditService.changingReject(supplier, comment, login.getId());
            }
            
            httpResult.success().message("已驳回");
            
        } catch (Exception e) {
            httpResult.fail("500").message("驳回操作失败");
        }
        
        return httpResult;
    }
    
}
